package org.javason.jsonrpc.impl;

import static org.javason.jsonrpc.JsonRpcConstants.ID;
import static org.javason.jsonrpc.JsonRpcConstants.METHOD;
import static org.javason.jsonrpc.JsonRpcConstants.PARAMS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.javason.jsonrpc.JsonRpcMessageContext;
import org.javason.util.Debug;

public class JsonRpcInvocationRequest {
	public static final String VERSION = "$Rev: 50408 $";
	private static final Logger LOG = Logger.getLogger(JsonRpcInvocationRequest.class);
	private JsonRpcMessageContext _messageContext;
	private JSONObject _jsonRequest;
	private String _methodName;
	
	private JsonRpcInvocationRequest() { }
	
	
	public JsonRpcInvocationRequest(String request) {
		setRequestString(request);
	}
	
	public JsonRpcInvocationRequest(JSONObject jsonRequest) {
		setJsonRequest(jsonRequest);
	}
	
	public Object getId() {
		return _jsonRequest.opt(ID);
	}
	
	public Object getParams() {
		Object result = null;
		try {
			if (hasArrayParams()) {
				result = _jsonRequest.getJSONArray(PARAMS);
			} else if (hasObjectParams()) {
				result = _jsonRequest.getJSONObject(PARAMS);
			}
		} catch (JSONException e) {
			LOG.error("Error getting PARAMS from request String", e);
		}
		return result;
	}
	
	public boolean hasArrayParams() {
		return (_jsonRequest.optJSONArray(PARAMS) != null);
	}
	
	public boolean hasObjectParams() {
		return (_jsonRequest.optJSONObject(PARAMS) != null);
	}
	
	public boolean isSystemMethod() {
		return (getMethodName().indexOf("system.") == 0);
	}
	
	
	public String getMethodName() {
		return _methodName;
	}

	/**
	 * @return the messageContext
	 */
	public JsonRpcMessageContext getMessageContext() {
		return _messageContext;
	}

	/**
	 * @param messageContext the messageContext to set
	 */
	public void setMessageContext(JsonRpcMessageContext messageContext) {
		_messageContext = messageContext;
	}
	
	
	/**
	 * @param jsonRequest the jsonRequest to set
	 */
	public void setJsonRequest(JSONObject jsonRequest) {
		_jsonRequest = jsonRequest;
		setMethodName();
	}

	
	private void setRequestString(String inputString) {
		try {
			setJsonRequest(JSONObject.fromObject(inputString));
		} catch (JSONException e) {
			LOG.error("Error setting request String", e);
		}
	}
	
	
	private void setMethodName() {
		try {
			_methodName = _jsonRequest.getString(METHOD);
		} catch (JSONException e) {
			LOG.error("Error setting METHOD from request String", e);
		}
	}

}
